﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace AtletIS.Shared.Helpers
{
    public static class FtpHelper
    {
        public static bool Upload(string filename, string ftpAdress, string ftpUser, string ftpPwd)
        {
            FileInfo iFile = new FileInfo(filename);
            string uri = "ftp://" + ftpAdress + "/" + iFile.Name;
            FtpWebRequest reqFTP;

            // Create FtpWebRequest object from the Uri provided
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));

            reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
            reqFTP.KeepAlive = false;
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = iFile.Length;

            // 2kB = 2048 / iFile.Length
            int buffLength = Convert.ToInt32(iFile.Length);
            byte[] buff = new byte[buffLength];
            int contentLen;

            // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
            FileStream fs = iFile.OpenRead();

            try
            {
                // Stream to which the file to be upload is written
                Stream strm = reqFTP.GetRequestStream();

                // Read from the file stream 2kb at a time
                contentLen = fs.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // Pomohlo?
                reqFTP.Abort();

                // Close the file stream and the Request Stream
                strm.Close();
                strm.Dispose();
                fs.Close();
                fs.Dispose();

                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
